Your First AI application¶

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Import Resources¶

In [1]:
# TODO: Make all necessary imports.
%matplotlib inline 
%config InlineBackend.figure_format ='retina'

import numpy as np
import tensorflow as tf
from tensorflow import keras 
from tensorflow.keras import layers
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
import tensorflow_hub as hub
import json
import random

print('Executed by Package Version:')
print("\t\u2022 numpy Version {}".format(np.__version__),end= '\n')
print("\t\u2022 Tensorflow Version {}".format(tf.__version__),end= '\n')
print("\t\u2022 Keras Version {}".format(keras.__version__),end='\n')
print("\t\u2022 GPU Devices {}".format(tf.config.list_physical_devices("GPU")),end='\n')
print("\t\u2022 CPU Devices {}".format(tf.config.list_physical_devices("CPU")),end='\n')
Executed by Package Version:
	• numpy Version 1.22.3
	• Tensorflow Version 2.9.1
	• Keras Version 2.9.0
	• GPU Devices [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
	• CPU Devices [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU')]

Load the Dataset¶

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [2]:
# TODO: Load the dataset with TensorFlow Datasets.
#flowers = tf.keras.utils.get_file(
#    'OxfordFlowers102',
#   'https://www.robots.ox.ac.uk/~vgg/data/flowers/102/102flowers.tgz',
#    untar=True)

#load extracted images from new keras extract path using data_dir parameter 
#copy the result into tensorflowd_dataset Folder on relative bath
#do not need the data_dir parameter anymore   

spliter = ['train' , 'validation' , 'test']

dataset , datasetinfo = tfds.load("oxford_flowers102",split=spliter,as_supervised=True,with_info = True)

# TODO: Create a training set, a validation set and a test set.
train_flowers , validate_flowers, test_flowers   = dataset

datasetinfo
Out[2]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
    in the United Kingdom. Each class consists of between 40 and 258 images. The images have
    large scale, pose and light variations. In addition, there are categories that have large
    variations within the category and several very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set.
    The training set and validation set each consist of 10 images per class (totalling 1020 images each).
    The test set consists of the remaining 6149 images (minimum 20 per class).
    
    Note: The dataset by default comes with a test size larger than the train
    size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_path='C:\\Users\\shaimaa soltan\\tensorflow_datasets\\oxford_flowers102\\2.1.1',
    file_format=tfrecord,
    download_size=328.90 MiB,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)

Explore the Dataset¶

In [3]:
# TODO: Get the number of examples in each set from the dataset info.
train_examples = datasetinfo.splits['train'].num_examples
validate_examples = datasetinfo.splits['validation'].num_examples
test_examples = datasetinfo.splits['test'].num_examples
classes = datasetinfo.features['label'].num_classes

print('\u2022 Total Number of Input examples {}'.format(train_examples + validate_examples + test_examples ))
print('')
print('\t\u2022 Total Number Train examples {}'.format(train_examples))
print('\t\u2022 Total Number validate examples {}'.format(validate_examples))
print('\t\u2022 Total Number test examples {}'.format(test_examples))
print('')
# TODO: Get the number of classes in the dataset from the dataset info.
print('\u2022 Total Number Output Classification Classes {}'.format(classes))
• Total Number of Input examples 8189

	• Total Number Train examples 1020
	• Total Number validate examples 1020
	• Total Number test examples 6149

• Total Number Output Classification Classes 102
In [4]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
i=0
for image, label in train_flowers.take(3):
    i=i+1
    print('The image[{0}] in the training set has:\n \t\u2022 Shape:{1} \n\t\u2022 Label:{2}'.format(i,image.shape, label))
The image[1] in the training set has:
 	• Shape:(500, 667, 3) 
	• Label:72
The image[2] in the training set has:
 	• Shape:(500, 666, 3) 
	• Label:84
The image[3] in the training set has:
 	• Shape:(670, 500, 3) 
	• Label:70
In [5]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding image label. 

for image, label in train_flowers.take(1):
    image = image.numpy().squeeze()
    grayimage = image[:,:,0]
    label = label.numpy()

fig , (axs1, axs2) = plt.subplots(1,2)

im = axs1.imshow(image)
axs1.set_title(label+1)
fig.colorbar(im,ax=axs1,orientation='horizontal')

im2=axs2.imshow(grayimage,cmap=plt.cm.gray)
axs2.axis('off')
axs2.set_title("{} in Gray".format(label+1))
fig.colorbar(im2,ax=axs2,orientation='horizontal')

plt.show()

print('The label of this image is:', label+1)
The label of this image is: 73

Label Mapping¶

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [6]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
In [7]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 

images = []
labels = []
for image, label in train_flowers.take(1):
    images.append(image.numpy().squeeze())
    labels.append(label.numpy())

plt.imshow(images[0])
plt.title(class_names.get(str(labels[0]+1)))
plt.colorbar()
plt.show()

print('The label of this image is:', labels[0]+1)
print('The category name of this Flower is:', class_names.get(str(labels[0]+1)))
The label of this image is: 73
The category name of this Flower is: water lily

Create Pipeline¶

In [8]:
# TODO: Create a pipeline for each set.
tf.keras.utils.set_random_seed(42)
#hash('setting keras random seed') % 2**32 -1)

config = {
    "Learning_Rate": 0.1,
    "Momentum":0.1,
    "Image_Shape": 224,
    "Batches": 60,
    "EPOCHS": 100,
    "Loss_Function":"sparse_categorical_crossentropy",
    "Architecture":"NN",
    "Dataset_Name":"oxford_flowers102",
    "Saved_Model_Name": "Keras_Flowers"
}

def ResizeNormalize(image ,label):
    image = tf.image.resize(image,(config.get("Image_Shape"),config.get("Image_Shape")))
    image = tf.cast(image,tf.float32)
    image /= 255
    label = label
    return image ,label

#train_flowers = train_flowers.map(lambda x, y: (data_augmentation(x, training=True), y))
#train_flowers_batch = train_flowers.shuffle(train_examples//4).map(lambda x, y: (data_augmentation(x, training=True), y)).map(ResizeNormalize).batch(config.get("Batch_Size")).prefetch(1)
#train_flowers_batch = train_flowers.shuffle(train_examples//4).map(ResizeNormalize).batch(config.get("Batches")).prefetch(1)

train_flowers_batch = train_flowers.map(ResizeNormalize).batch(config.get("Batches")).prefetch(1)

validate_flowers_batch =  validate_flowers.map(ResizeNormalize).batch(config.get("Batches")).prefetch(1) 

test_flowers_batch =  test_flowers.map(ResizeNormalize).batch(config.get("Batches")).prefetch(1) 


plt.figure(figsize=(16, 10))
j = 0
for image, lable in train_flowers_batch.take(5):
    images = image.numpy().squeeze()
    label=lable.numpy()
    ax = plt.subplot(1, 5, j + 1)
    plt.imshow(images[j])
    if str(label[j]) in class_names.keys():
        plt.title(str(label[j]+1) + '-' + class_names.get(str(label[j]+1)))
    else:
        plt.title(str(label[j]+1)) 
    plt.axis("off")
    j=j+1

plt.show()
   

print("images resized to shape {}".format(images[0].shape))


img_augmentation = keras.models.Sequential(
    [
        layers.RandomRotation(factor=0.15),
        layers.RandomTranslation(height_factor=0.1, width_factor=0.1),
        layers.RandomFlip(),
        layers.RandomContrast(factor=0.1)
    ],
    name="img_augmentation",
)

plt.figure(figsize=(16, 10))
for image, label in train_flowers.take(1):
    for i in range(16):
        ax = plt.subplot(4, 4, i + 1)
        image = img_augmentation(image, training=True)
        plt.imshow(image.numpy().astype("uint8"))
        plt.title("Augmented {}".format(label+1))
        plt.axis("off")

plt.show()
images resized to shape (224, 224, 3)

Build and Train the Classifier¶

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [9]:
# TODO: Build and train your network.
#1 - Clear session 
keras.backend.clear_session()

#2 load Pre trained model mobilenet_v2
#Pretrained_network_URL =  "https://tfhub.dev/google/imagenet/mobilenet_v2_130_224/classification/5"
Pretrained_network_URL =  "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
PreTrained_Feature_extractor = hub.KerasLayer(Pretrained_network_URL,trainable = False,input_shape= (config.get("Image_Size"),config.get("Image_Size"),3))
#3 create keras model

model = keras.Sequential([
    PreTrained_Feature_extractor,
    keras.layers.Dense(2048,activation='relu'),
    keras.layers.Dropout(0.5),
    keras.layers.Dense(classes , activation='softmax')
])

model.summary()

#4 compile model
model.compile(optimizer = 'adam' , loss= 'sparse_categorical_crossentropy' ,metrics=['accuracy'])

#5 hendel overfitting (early stoping) 
train_callbacks = [
    keras.callbacks.EarlyStopping(
        monitor="val_loss", patience=6, restore_best_weights=True
    )    
]

#6 fit and trian the model
history = model.fit(
        train_flowers_batch,
        batch_size=config.get('Batches'),
        epochs=config.get('EPOCHS'),
        validation_data=validate_flowers_batch,
        callbacks=train_callbacks,
)
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 2048)              2623488   
                                                                 
 dropout (Dropout)           (None, 2048)              0         
                                                                 
 dense_1 (Dense)             (None, 102)               208998    
                                                                 
=================================================================
Total params: 5,090,470
Trainable params: 2,832,486
Non-trainable params: 2,257,984
_________________________________________________________________
Epoch 1/100
17/17 [==============================] - 10s 240ms/step - loss: 4.2237 - accuracy: 0.1245 - val_loss: 2.6481 - val_accuracy: 0.4941
Epoch 2/100
17/17 [==============================] - 3s 208ms/step - loss: 1.7757 - accuracy: 0.6039 - val_loss: 1.4564 - val_accuracy: 0.6961
Epoch 3/100
17/17 [==============================] - 3s 208ms/step - loss: 0.7841 - accuracy: 0.8088 - val_loss: 1.0285 - val_accuracy: 0.7588
Epoch 4/100
17/17 [==============================] - 3s 210ms/step - loss: 0.3595 - accuracy: 0.9314 - val_loss: 0.8774 - val_accuracy: 0.7667
Epoch 5/100
17/17 [==============================] - 3s 210ms/step - loss: 0.2057 - accuracy: 0.9627 - val_loss: 0.8088 - val_accuracy: 0.8000
Epoch 6/100
17/17 [==============================] - 3s 211ms/step - loss: 0.1210 - accuracy: 0.9853 - val_loss: 0.7667 - val_accuracy: 0.7971
Epoch 7/100
17/17 [==============================] - 3s 204ms/step - loss: 0.0914 - accuracy: 0.9853 - val_loss: 0.7891 - val_accuracy: 0.7912
Epoch 8/100
17/17 [==============================] - 3s 210ms/step - loss: 0.0690 - accuracy: 0.9912 - val_loss: 0.7220 - val_accuracy: 0.8167
Epoch 9/100
17/17 [==============================] - 4s 211ms/step - loss: 0.0494 - accuracy: 0.9980 - val_loss: 0.7166 - val_accuracy: 0.8029
Epoch 10/100
17/17 [==============================] - 4s 213ms/step - loss: 0.0416 - accuracy: 0.9971 - val_loss: 0.7043 - val_accuracy: 0.8216
Epoch 11/100
17/17 [==============================] - 4s 219ms/step - loss: 0.0320 - accuracy: 0.9980 - val_loss: 0.7034 - val_accuracy: 0.8069
Epoch 12/100
17/17 [==============================] - 4s 229ms/step - loss: 0.0266 - accuracy: 0.9990 - val_loss: 0.6842 - val_accuracy: 0.8167
Epoch 13/100
17/17 [==============================] - 4s 227ms/step - loss: 0.0221 - accuracy: 1.0000 - val_loss: 0.6929 - val_accuracy: 0.8265
Epoch 14/100
17/17 [==============================] - 4s 242ms/step - loss: 0.0190 - accuracy: 0.9990 - val_loss: 0.6903 - val_accuracy: 0.8176
Epoch 15/100
17/17 [==============================] - 4s 244ms/step - loss: 0.0202 - accuracy: 0.9980 - val_loss: 0.6956 - val_accuracy: 0.8127
Epoch 16/100
17/17 [==============================] - 4s 245ms/step - loss: 0.0168 - accuracy: 0.9990 - val_loss: 0.6885 - val_accuracy: 0.8039
Epoch 17/100
17/17 [==============================] - 4s 248ms/step - loss: 0.0114 - accuracy: 1.0000 - val_loss: 0.6676 - val_accuracy: 0.8216
Epoch 18/100
17/17 [==============================] - 4s 245ms/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.6561 - val_accuracy: 0.8304
Epoch 19/100
17/17 [==============================] - 4s 240ms/step - loss: 0.0094 - accuracy: 1.0000 - val_loss: 0.6810 - val_accuracy: 0.8186
Epoch 20/100
17/17 [==============================] - 4s 244ms/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.6620 - val_accuracy: 0.8235
Epoch 21/100
17/17 [==============================] - 4s 247ms/step - loss: 0.0066 - accuracy: 1.0000 - val_loss: 0.6466 - val_accuracy: 0.8225
Epoch 22/100
17/17 [==============================] - 4s 240ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.6558 - val_accuracy: 0.8225
Epoch 23/100
17/17 [==============================] - 4s 241ms/step - loss: 0.0067 - accuracy: 1.0000 - val_loss: 0.6575 - val_accuracy: 0.8304
Epoch 24/100
17/17 [==============================] - 4s 233ms/step - loss: 0.0071 - accuracy: 1.0000 - val_loss: 0.6591 - val_accuracy: 0.8294
Epoch 25/100
17/17 [==============================] - 4s 247ms/step - loss: 0.0072 - accuracy: 1.0000 - val_loss: 0.6843 - val_accuracy: 0.8127
Epoch 26/100
17/17 [==============================] - 4s 246ms/step - loss: 0.0057 - accuracy: 1.0000 - val_loss: 0.6517 - val_accuracy: 0.8284
Epoch 27/100
17/17 [==============================] - 4s 254ms/step - loss: 0.0045 - accuracy: 1.0000 - val_loss: 0.6489 - val_accuracy: 0.8363
In [10]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

def plot_hist(hist):
    plt.plot(hist.history["accuracy"])
    plt.plot(hist.history["val_accuracy"])
    plt.plot(hist.history["loss"])
    plt.plot(hist.history["val_loss"])
    plt.title("Training Progress")
    plt.ylabel("Accuracy/Loss")
    plt.xlabel("Epochs")
    plt.legend(["train_acc", "val_acc", "train_loss", "val_loss"], loc="upper left")
    plt.show()
    
plot_hist(history)

training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(len(training_accuracy))

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network¶

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [11]:
# TODO: Print the loss and accuracy values achieved on the entire test set.

loss = model.evaluate(validate_flowers_batch)[0] * 100
print("Loss on Validation set: {:.2f}%".format(loss))

accuracy = model.evaluate(validate_flowers_batch)[1] * 100
print("Accuracy on validation set: {:.2f}%".format(accuracy))

loss = model.evaluate(test_flowers_batch)[0] * 100
print("Loss on test set: {:.2f}%".format(loss))

accuracy = model.evaluate(test_flowers_batch)[1] * 100
print("Accuracy on test set: {:.2f}%".format(accuracy))
17/17 [==============================] - 2s 97ms/step - loss: 0.6466 - accuracy: 0.8225
Loss on Validation set: 64.66%
17/17 [==============================] - 2s 98ms/step - loss: 0.6466 - accuracy: 0.8225
Accuracy on validation set: 82.25%
103/103 [==============================] - 11s 102ms/step - loss: 0.7966 - accuracy: 0.7961
Loss on test set: 79.66%
103/103 [==============================] - 10s 98ms/step - loss: 0.7966 - accuracy: 0.7961
Accuracy on test set: 79.61%

Save the Model¶

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [12]:
# TODO: Save your trained model as a Keras model.
model.save('./{}.h5'.format(config.get('Saved_Model_Name')))

Load the Keras Model¶

Load the Keras model you saved above.

In [13]:
# TODO: Load the Keras model
Saved_model = tf.keras.models.load_model('./{}.h5'.format(config.get('Saved_Model_Name')),custom_objects={'KerasLayer':hub.KerasLayer})

Inference for Classification¶

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing¶

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [14]:
# TODO: Create the process_image function
def process_image(image):
    processed_image =  tf.image.resize(tf.convert_to_tensor(image),(config.get("Image_Shape"),config.get("Image_Shape")))
    image = tf.cast(image,tf.float32)
    processed_image = processed_image / 255.0
    return processed_image.numpy()

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [15]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference¶

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [16]:
# TODO: Create the predict function
def predict(image_path , model, top_k):
    if top_k <=0: top_k = 1
    with Image.open(image_path) as image:
        #print(np.asarray(image).shape)
        processed_Image = process_image(np.asarray(image))
        #print(processed_Image.shape)
        probs = model.predict(np.expand_dims(processed_Image,axis=0))
        sorted_probs = sorted(probs[0] , reverse = True)
        a = np.array(probs[:top_k])
        Class_key = sorted(range(len(probs[0])),key= lambda sub : probs[0][sub], reverse = True)[:top_k]
    return sorted_probs[:top_k] , list(map(lambda x: x+1 , Class_key))

Sanity Check¶

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [17]:
# TODO: Plot the input image along with the top 5 classes
image_path = './test_images/wild_pansy.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)
TopN =5

probs , classes  = predict(image_path, Saved_model, TopN)
print('Prediction : ')
print("TOP {0} Probabilities = {1} ".format(TopN ,probs))
print("TOP {0} Flower Labels = {1}".format(TopN,classes))
classes = list(map(lambda x: class_names.get(str(x)),classes))
print("TOP {0} Flower Class Names = {1}".format(TopN,classes))
fig, (ax1, ax2) = plt.subplots(figsize=(10,4), ncols=2)

ax1.imshow(test_image)
ax1.set_axis_off()
ax2.barh(classes,probs)
ax2.set_title('Class Probability')
ax2.invert_yaxis()
plt.tight_layout()
plt.show()
1/1 [==============================] - 1s 938ms/step
Prediction : 
TOP 5 Probabilities = [0.99995625, 9.105672e-06, 7.3015153e-06, 7.020553e-06, 4.4961885e-06] 
TOP 5 Flower Labels = [52, 19, 64, 34, 82]
TOP 5 Flower Class Names = ['wild pansy', 'balloon flower', 'silverbush', 'mexican aster', 'clematis']
In [ ]: